<template>
  <view class="scan-button">
    <button 
      class="scan-btn" 
      :class="{ 'scan-btn-disabled': disabled }"
      :disabled="disabled"
      @tap="handleScan"
    >
      <view class="scan-icon">
        <text class="iconfont icon-scan"></text>
      </view>
      <text class="scan-text">{{ buttonText }}</text>
    </button>
    
    <!-- 扫码结果弹窗 -->
    <u-popup 
      v-model="showResult" 
      mode="center" 
      border-radius="16"
      :closeable="true"
    >
      <view class="result-popup">
        <view class="result-header">
          <text class="result-title">扫码结果</text>
        </view>
        <view class="result-content">
          <view class="result-item">
            <text class="result-label">类型：</text>
            <text class="result-value">{{ resultInfo.typeText }}</text>
          </view>
          <view class="result-item">
            <text class="result-label">数据：</text>
            <text class="result-value">{{ resultInfo.dataText }}</text>
          </view>
        </view>
        <view class="result-actions">
          <button class="action-btn confirm" @tap="confirmResult">确认</button>
          <button class="action-btn cancel" @tap="cancelResult">取消</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { parseScanData } from '@/utils/warehouse.js'

export default {
  name: 'ScanButton',
  props: {
    buttonText: {
      type: String,
      default: '扫码'
    },
    scanType: {
      type: String,
      default: 'all', // all, batch, weight, material, contract
      validator: (value) => ['all', 'batch', 'weight', 'material', 'contract'].includes(value)
    },
    disabled: {
      type: Boolean,
      default: false
    },
    autoConfirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showResult: false,
      scanResult: null,
      resultInfo: {
        typeText: '',
        dataText: ''
      }
    }
  },
  methods: {
    async handleScan() {
      if (this.disabled) return
      
      try {
        // #ifdef H5
        this.handleH5Scan()
        // #endif
        
        // #ifdef APP-PLUS || MP-WEIXIN
        this.handleAppScan()
        // #endif
      } catch (error) {
        uni.showToast({
          title: '扫码失败：' + error.message,
          icon: 'none'
        })
      }
    },
    
    handleH5Scan() {
      // H5端模拟扫码
      uni.showModal({
        title: '模拟扫码',
        content: '请输入扫码内容：',
        editable: true,
        placeholderText: '例如：BATCH:ABC123',
        success: (res) => {
          if (res.confirm && res.content) {
            this.processScanResult(res.content)
          }
        }
      })
    },
    
    handleAppScan() {
      // APP端真实扫码
      uni.scanCode({
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
          this.processScanResult(res.result)
        },
        fail: (err) => {
          uni.showToast({
            title: '扫码失败：' + err.errMsg,
            icon: 'none'
          })
        }
      })
    },
    
    processScanResult(result) {
      const parsed = parseScanData(result)
      
      if (!parsed.success) {
        uni.showToast({
          title: parsed.message,
          icon: 'none'
        })
        return
      }
      
      // 检查扫码类型
      if (this.scanType !== 'all' && parsed.type !== this.scanType) {
        uni.showToast({
          title: `请扫描${this.getTypeText(this.scanType)}类型`,
          icon: 'none'
        })
        return
      }
      
      this.scanResult = parsed
      this.resultInfo = this.formatResultInfo(parsed)
      
      if (this.autoConfirm) {
        this.confirmResult()
      } else {
        this.showResult = true
      }
    },
    
    formatResultInfo(result) {
      const typeMap = {
        batch: '批号',
        weight: '重量',
        material: '物料',
        contract: '合同'
      }
      
      let dataText = ''
      switch (result.type) {
        case 'batch':
          dataText = result.data.batchNo
          break
        case 'weight':
          dataText = `${result.data.weight} kg`
          break
        case 'material':
          dataText = result.data.materialCode
          break
        case 'contract':
          dataText = result.data.contractCode
          break
      }
      
      return {
        typeText: typeMap[result.type] || result.type,
        dataText
      }
    },
    
    getTypeText(type) {
      const typeMap = {
        batch: '批号',
        weight: '重量',
        material: '物料',
        contract: '合同'
      }
      return typeMap[type] || type
    },
    
    confirmResult() {
      this.showResult = false
      this.$emit('scan-success', this.scanResult)
    },
    
    cancelResult() {
      this.showResult = false
      this.scanResult = null
      this.$emit('scan-cancel')
    }
  }
}
</script>

<style lang="scss" scoped>
.scan-button {
  display: inline-block;
}

.scan-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
  border: none;
  border-radius: 8rpx;
  color: #fff;
  font-size: 28rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 122, 255, 0.3);
  
  &:active {
    transform: scale(0.95);
  }
  
  &.scan-btn-disabled {
    background: #ccc;
    box-shadow: none;
    opacity: 0.6;
  }
}

.scan-icon {
  margin-right: 8rpx;
  
  .iconfont {
    font-size: 32rpx;
  }
}

.scan-text {
  font-weight: 500;
}

.result-popup {
  width: 600rpx;
  padding: 40rpx;
  
  .result-header {
    text-align: center;
    margin-bottom: 30rpx;
    
    .result-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .result-content {
    margin-bottom: 40rpx;
    
    .result-item {
      display: flex;
      margin-bottom: 20rpx;
      
      .result-label {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
        min-width: 100rpx;
      }
      
      .result-value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .result-actions {
    display: flex;
    gap: 20rpx;
    
    .action-btn {
      flex: 1;
      padding: 20rpx;
      border: none;
      border-radius: 8rpx;
      font-size: 28rpx;
      
      &.confirm {
        background: #007AFF;
        color: #fff;
      }
      
      &.cancel {
        background: #f5f5f5;
        color: #666;
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
}
</style>